package repository

import (
	"fmt"
	"gorm.io/gorm"
	"guliedu/model"
)

type IEduSubjectRepository interface {
	// 获取所有的分类和子分类信息
	SelectAllSubjectByOne() ([]model.EduSubject, error)

	// 获取所有一级分类
	SelectOneSubject() ([]model.EduSubject, error)

	// 根据名称查询分类
	SelectSubjectByTitle(title string) (*model.EduSubject, error)

	// 添加分类
	Insert(s *model.EduSubject) error

	// 查询所有分类
	Select() ([]model.EduSubject, error)

	// 根据ID查询分类
	SelectByCourseID(id string) (*model.EduSubject, error)
}

func NewIEduSubjectRepository() IEduSubjectRepository {
	return &EduSubjectRepository{mysqlDb: db}
}

type EduSubjectRepository struct {
	mysqlDb *gorm.DB
}

func (r *EduSubjectRepository) SelectSubjectByTitle(title string) (course *model.EduSubject, err error) {
	err = r.mysqlDb.Where("title = ?", title).Find(&course).Error
	return
}

func (r *EduSubjectRepository) Insert(s *model.EduSubject) error {
	fmt.Println(s)
	return db.Create(&s).Error
}

func (r *EduSubjectRepository) SelectOneSubject() (courses []model.EduSubject, err error) {
	err = db.Where("parent_id = ?", 1).Find(&courses).Error
	return
}

func (r *EduSubjectRepository) SelectAllSubjectByOne() (courses []model.EduSubject, err error) {
	err = db.Preload("Subjects").Where("parent_id = ?", 1).Find(&courses).Error
	return
}

func (r *EduSubjectRepository) Select() (courses []model.EduSubject, err error) {
	err = db.Not("id = ?", 1).Find(&courses).Error
	return
}

func (r *EduSubjectRepository) SelectByCourseID(id string) (subject *model.EduSubject, err error) {
	err = r.mysqlDb.Where("id = ?", id).Find(&subject).Error
	return
}
